﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Vehicle.Model;
using Yipusoft.Vehicle.BLL;
using Yipusoft.SoldierArchives.BLL;
using Yipusoft.SoldierArchives.Model;
using System.IO;


public partial class BasicBase_Vehicle_VehicleNew : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            init();

        }
    }

    void BindddlDriver()
    {
        ddlDriver.Items.Clear();
        if (ddlClass.SelectedValue == "101008" || ddlClass.SelectedValue == "102006" || ddlClass.SelectedValue == "102007" || ddlClass.SelectedValue == "102003" || ddlType.SelectedValue == "1030")
        {

            trDriver.Visible = true;
            Soldier soldier = new Soldier();
            string where = " DepartmentId='" + UnitList.SelectedValue + "' and isDelete=0 ";
            ddlDriver.Items.Add(new ListItem("--------", ""));
            ddlDriver.DataSource = soldier.GetSoldiersByWhere(where, "CardID", "desc", 10000, 0);
            ddlDriver.DataBind();
        }
        else
        {
            trDriver.Visible = false;
        }
    }

    int _limitwidth = 640;
    int _limitheight = 480;
    void init()
    {

        //部门

        UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
        if (userInfo.DepartmentID.Substring(0, 4) == "1300")
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') ");
            DepartmentList.DataBind();
            DepartmentListBind();
        }
        else
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + department.DepartmentID.Substring(0, 4) + "000' ");
            DepartmentList.DataBind();
            DepartmentListBind();
        }
        //车辆类型

        ddlType.DataTextField = "ItemName";
        ddlType.DataValueField = "ItemID";
        ddlType.DataSource = CodeItem.GetList2(" GroupID='XFZBLB' and ParentID='10' and ItemID<>'1099' order by SeqID,ItemID ");
        ddlType.DataBind();
        ddlClass.DataTextField = "ItemName";
        ddlClass.DataValueField = "ItemID";
        BindClass();
        ////车辆状态
        //rblState.DataTextField = "ItemName";
        //rblState.DataValueField = "ItemID";
        //rblState.DataSource = CodeItem.GetList2(" GroupID='XFCLZT' and ParentID='' order by SeqID,ItemID ");
        //rblState.DataBind();
        //邦定

        UnitList.SelectedValue = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        if (Request.QueryString["id"] != null)
        {
            if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200600") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200602"))
            {
                Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                return;
            }
            ActionTitle.Text = "修改车辆";

            VehicleInfo info = Vehicle.GetDetail(new Guid(Request.QueryString["id"]));
            Address.Text = info.Address;
            AlertInfo.Text = info.AlertInfo;
            CapacityOfFoam.Text = DecimalToString(info.CapacityOfFoam);
            CapacityOfPowder.Text = DecimalToString(info.CapacityOfPowder);
            CapacityOfWater.Text = DecimalToString(info.CapacityOfWater);
            ChassisType.Text = info.ChassisType;
            ConstantPressure.Text = DecimalToString(info.ConstantPressure);
            DateProduc.Text = DateTimeToString(info.DateProduc);
            DatePurchase.Text = DateTimeToString(info.DatePurchase);
            //---------------部门：先指定其selectValue后梆定部门------------------------------------------------
            DepartmentList.SelectedValue = info.DepartmentID.Substring(0, 4) + "000";
            UnitList.SelectedValue = info.DepartmentID;
            DepartmentListBind();

            NumberPlate.Text = info.NumberPlate;
            EngineType.Text = info.EngineType;
            //FlowRate.Text = DecimalToString(info.FlowRate);
            Life.Text = IntToString(info.Life);
            Manufacturer.Text = info.Manufacturer;
            MaxPower.Text = DecimalToString(info.MaxPower);
            MaxSpeed.Text = DecimalToString(info.MaxSpeed);
            MaxTorque.Text = DecimalToString(info.MaxTorque);
            MostUse.Text = info.MostUse;
            OtherParameters.Text = info.OtherParameters;
            Passenger.Text = IntToString(info.Passenger);
            Phone.Text = info.Phone;
            Price.Text = DecimalToString(info.Price);
            // rblState.SelectedValue = info.State;

            TotalWeight.Text = DecimalToString(info.TotalWeight);
            UseMethod.Text = info.UseMethod;
            ddlType.SelectedValue = CodeItem.GetCodeItem(info.VehicleClass, "XFZBLB").ParentID;
            ddlClass.SelectedValue = info.VehicleClass;
            BindClass();

            VehicleMode.Text = info.VehicleMode;
            VehicleName.Text = info.VehicleName;
            WorkHeight.Text = DecimalToString(info.WorkHeight);
            Wlan.Checked = Convert.ToBoolean(info.Wlan);
            VehicleWidth.Text = DecimalToString(info.VehicleWidth);
            VehicleLength.Text = DecimalToString(info.VehicleLength);
            VehicleHeight.Text = DecimalToString(info.VehicleHeight);
            // soldierCount.Text = IntToString(info.soldierCount);
            RadioNO.Text = info.RadioNO;
            PumpType.Text = info.PumpType;
            PumpFlux.Text = DecimalToString(info.PumpFlux);
            MaxDrinkDepth.Text = DecimalToString(info.MaxDrinkDepth);
            Number.Text = info.Number;


            BindddlDriver();
            //司机
            string DriverWhere = "VehicleId='" + info.VehicleID + "'";
            VehicleDriverInfo DriverInfo = VehicleDriver.GetList(DriverWhere, 0, 1000).FirstOrDefault();
            if (DriverInfo != null)
            {
                ddlDriver.SelectedValue = DriverInfo.SoldierId.ToString();
            }
        }
        else
        {
            if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200600") && !Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "200601"))
            {
                Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                return;
            }
            ActionTitle.Text = "添加车辆";
            BindddlDriver();
        }

    }

    protected void DepartmentList_TextChanged(object sender, EventArgs e)
    {
        DepartmentListBind();
        BindddlDriver();
    }

    void DepartmentListBind()
    {
        UnitList.Items.Clear();
        string strWhere = "(departmentid like '" + DepartmentList.SelectedValue.Substring(0, 4) + "%'  and  SUBSTRING(DepartmentID, 5, 1)<>'0') or departmentid='" + DepartmentList.SelectedValue + "'";
        UnitList.DataSource = Department.GetList(strWhere);
        UnitList.DataBind();
    }
    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClass();
        BindddlDriver();
    }

    private void BindClass()
    {
        ddlClass.Items.Clear();
        ddlClass.DataSource = CodeItem.GetList2(" GroupID='XFZBLB' and  parentID='" + ddlType.SelectedValue + "' order by ItemID,SeqID ");
        ddlClass.DataBind();
    }
    //保存
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            //修改
            VehicleInfo info = Vehicle.GetDetail(new Guid(Request.QueryString["id"]));
            string path = Server.MapPath("pics\\");
            string word = info.Picture;
            if (Picture.HasFile)
            {
                string ex = Picture.FileName.Substring(Picture.FileName.LastIndexOf('.') + 1);
                if (ex.ToLower() != "jpg" && ex.ToLower() != "png" && ex.ToLower() != "gif" && ex.ToLower() != "bmp")
                {
                    Prompt.Text = "提示:上传图片格式错误!";
                    return;
                }
                else
                {
                    if (Picture.FileContent.Length / 1024 / 1024 > 5)
                    {

                        Prompt.Text = "提示:上传文档不可大于5M!";
                        return;
                    }
                    else
                    {
                        Stream oStream = Picture.PostedFile.InputStream;
                        System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                        int owidth = oImage.Width; //原图宽度
                        int oheight = oImage.Height; //原图高度

                        if (owidth > _limitwidth || oheight > _limitheight)
                        {

                            Prompt.Text = "超过允许的图片尺寸(" + _limitwidth.ToString() + "×" + _limitheight.ToString() + ")范围!";
                            return;

                        }//检查是否超出规定尺寸
                        if (word != "")
                        {
                            FileInfo file = new FileInfo(path + word);
                            if (file.Exists)
                            {
                                file.IsReadOnly = false;
                                file.Delete();
                            }
                        }
                        word = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + "." + ex;
                        Picture.SaveAs(path + word);
                        info.Picture = word;
                    }
                }
            }
            info.Address = Address.Text;
            info.AlertInfo = AlertInfo.Text;
            info.CapacityOfFoam = CapacityOfFoam.Text == "" ? -1 : Convert.ToDecimal(CapacityOfFoam.Text);
            info.CapacityOfPowder = CapacityOfPowder.Text == "" ? -1 : Convert.ToDecimal(CapacityOfPowder.Text);
            info.CapacityOfWater = CapacityOfWater.Text == "" ? -1 : Convert.ToDecimal(CapacityOfWater.Text);
            info.ChassisType = ChassisType.Text;
            info.ConstantPressure = ConstantPressure.Text == "" ? -1 : Convert.ToDecimal(ConstantPressure.Text);
            info.DateProduc = DateProduc.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DateProduc.Text);
            info.DatePurchase = DatePurchase.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DatePurchase.Text);

            info.DepartmentID = UnitList.SelectedValue;
            info.EngineType = EngineType.Text;
            //info.FlowRate = StringToDecimal(FlowRate.Text);
            info.Life = StringToInt(Life.Text);
            info.Manufacturer = Manufacturer.Text;
            info.MaxPower = StringToDecimal(MaxPower.Text);
            info.MaxSpeed = StringToDecimal(MaxSpeed.Text);
            info.MaxTorque = StringToDecimal(MaxTorque.Text);
            info.MostUse = MostUse.Text;
            info.OtherParameters = OtherParameters.Text;
            info.Passenger = StringToInt(Passenger.Text);
            info.Phone = Phone.Text;
            info.Price = StringToDecimal(Price.Text);
            //info.State = rblState.SelectedValue;
            info.TimeLastModified = DateTime.Now;
            info.TotalWeight = StringToDecimal(TotalWeight.Text);
            info.UseMethod = UseMethod.Text;
            info.VehicleClass = ddlClass.SelectedValue;
            info.VehicleMode = VehicleMode.Text;
            info.VehicleName = VehicleName.Text;
            info.NumberPlate = NumberPlate.Text;
            info.WorkHeight = StringToDecimal(WorkHeight.Text);
            info.Wlan = Convert.ToInt32(Wlan.Checked);
            info.VehicleWidth = StringToDecimal(VehicleWidth.Text);
            info.VehicleLength = StringToDecimal(VehicleLength.Text);
            info.VehicleHeight = StringToDecimal(VehicleHeight.Text);
            //info.soldierCount = StringToInt(soldierCount.Text);
            info.RadioNO = RadioNO.Text;
            info.PumpType = PumpType.Text;
            info.PumpFlux = StringToDecimal(PumpFlux.Text);
            info.MaxDrinkDepth = StringToDecimal(MaxDrinkDepth.Text);
            info.Number = Number.Text.ToString();
            if (Vehicle.Update(info))
            {
                //司机
                if (ddlDriver.SelectedValue != "")
                {
                    string where = " VehicleId='" + Request["id"] + "' ";
                    VehicleDriverInfo driver = VehicleDriver.GetList(where, 0, 1).FirstOrDefault();
                    if (driver != null)
                    {
                        VehicleDriver.Delete(driver.Id);
                    }


                    driver = new VehicleDriverInfo();
                    driver.Id = Guid.NewGuid();
                    driver.VehicleId = info.VehicleID;
                    driver.SetDate = DateTime.Now;
                    driver.SetUserId = Page.User.Identity.Name;
                    driver.SoldierId = new Guid(ddlDriver.SelectedValue);

                    VehicleDriver.Insert(driver);
                }
                else
                {
                    string where = " VehicleId='" + Request["id"] + "' ";
                    VehicleDriverInfo driver = VehicleDriver.GetList(where, 0, 1).FirstOrDefault();
                    if (driver != null)
                    {
                        VehicleDriver.Delete(driver.Id);
                    }
                }


                EventLogInfo log = new EventLogInfo();
                log.EventTime = DateTime.Now;
                log.EventType = 1;
                log.EventData = "修改新记录";
                log.ItemID = Request.QueryString["id"];
                log.ItemName = "Vehicle";
                log.ItemFullUrl = "Vehicle/VehicleNew.aspx";
                log.CreatedBy = Context.User.Identity.Name;
                log.CreatedTime = DateTime.Now;
                log.UserIP = Request.UserHostAddress;
                EventLog.Insert(log);

                Prompt.Text = "提示：更新成功！";
            }
            else
            {
                Prompt.Text = "提示：更新失败！";
            }

        }
        else
        {
            //添加
            VehicleInfo info = new VehicleInfo();
            string path = Server.MapPath("pics\\");
            string word = "";
            if (Picture.HasFile)
            {
                string ex = Picture.FileName.Substring(Picture.FileName.LastIndexOf('.') + 1);
                if (ex.ToLower() != "jpg" && ex.ToLower() != "png" && ex.ToLower() != "gif" && ex.ToLower() != "bmp")
                {
                    Prompt.Text = "提示:上传图片格式错误!";
                    return;
                }
                else
                {
                    if (Picture.FileContent.Length / 1024 / 1024 > 5)
                    {

                        Prompt.Text = "提示:上传文档不可大于5M!";
                        return;
                    }
                    else
                    {
                        Stream oStream = Picture.PostedFile.InputStream;
                        System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                        int owidth = oImage.Width; //原图宽度
                        int oheight = oImage.Height; //原图高度

                        if (owidth > _limitwidth || oheight > _limitheight)
                        {

                            Prompt.Text = "超过允许的图片尺寸(" + _limitwidth.ToString() + "×" + _limitheight.ToString() + ")范围!";
                            return;

                        }//检查是否超出规定尺寸

                        word = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + "." + ex;

                        Picture.SaveAs(path + word);

                    }
                }
            }
            info.Picture = word;
            info.Address = Address.Text;
            info.AlertInfo = AlertInfo.Text;
            info.CapacityOfFoam = CapacityOfFoam.Text == "" ? -1 : Convert.ToDecimal(CapacityOfFoam.Text);
            info.CapacityOfPowder = CapacityOfPowder.Text == "" ? -1 : Convert.ToDecimal(CapacityOfPowder.Text);
            info.CapacityOfWater = CapacityOfWater.Text == "" ? -1 : Convert.ToDecimal(CapacityOfWater.Text);
            info.ChassisType = ChassisType.Text;
            info.ConstantPressure = ConstantPressure.Text == "" ? -1 : Convert.ToDecimal(ConstantPressure.Text);
            info.DateProduc = DateProduc.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DateProduc.Text);
            info.DatePurchase = DatePurchase.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DatePurchase.Text);

            info.DepartmentID = UnitList.SelectedValue;
            info.EngineType = EngineType.Text;
            //info.FlowRate = StringToDecimal(FlowRate.Text);
            info.Life = StringToInt(Life.Text);
            info.Manufacturer = Manufacturer.Text;
            info.MaxPower = StringToDecimal(MaxPower.Text);
            info.MaxSpeed = StringToDecimal(MaxSpeed.Text);
            info.MaxTorque = StringToDecimal(MaxTorque.Text);
            info.MostUse = MostUse.Text;
            info.OtherParameters = OtherParameters.Text;
            info.Passenger = StringToInt(Passenger.Text);
            info.Phone = Phone.Text;
            info.Price = StringToDecimal(Price.Text);
            //info.State = rblState.SelectedValue;
            info.TimeLastModified = DateTime.Now;
            info.TotalWeight = StringToDecimal(TotalWeight.Text);
            info.UseMethod = UseMethod.Text;
            info.VehicleClass = ddlClass.SelectedValue;
            info.VehicleMode = VehicleMode.Text;
            info.VehicleName = VehicleName.Text;
            info.NumberPlate = NumberPlate.Text;
            info.WorkHeight = StringToDecimal(WorkHeight.Text);
            info.Wlan = Convert.ToInt32(Wlan.Checked);
            info.VehicleWidth = StringToDecimal(VehicleWidth.Text);
            info.VehicleLength = StringToDecimal(VehicleLength.Text);
            info.VehicleHeight = StringToDecimal(VehicleHeight.Text);
            //info.soldierCount = StringToInt("0");
            info.RadioNO = RadioNO.Text;
            info.PumpType = PumpType.Text;
            info.PumpFlux = StringToDecimal(PumpFlux.Text);
            info.MaxDrinkDepth = StringToDecimal(MaxDrinkDepth.Text);
            info.Number = Number.Text.ToString();

            Guid id = Vehicle.Insert(info);
            if (id != Guid.Empty)
            {
                //司机
                if (ddlDriver.SelectedValue != "")
                {
                    VehicleDriverInfo driver = new VehicleDriverInfo();
                    driver.Id = Guid.NewGuid();
                    driver.VehicleId = id;
                    driver.SetDate = DateTime.Now;
                    driver.SetUserId = Page.User.Identity.Name;
                    driver.SoldierId = new Guid(ddlDriver.SelectedValue);
                    VehicleDriver.Insert(driver);
                }
                EventLogInfo log = new EventLogInfo();
                log.EventTime = DateTime.Now;
                log.EventType = 1;
                log.EventData = "添加新记录";
                log.ItemID = id.ToString();
                log.ItemName = "Vehicle";
                log.ItemFullUrl = "Vehicle/VehicleNew.aspx";
                log.CreatedBy = Context.User.Identity.Name;
                log.CreatedTime = DateTime.Now;
                log.UserIP = Request.UserHostAddress;
                EventLog.Insert(log);

                Prompt.Text = "提示：添加成功！";
            }
            else
            {
                Prompt.Text = "提示：添加失败！";
            }
        }
    }

    DateTime StringToDateTime(string strDate)
    {
        return strDate == "" ? DateTime.MaxValue : Convert.ToDateTime(strDate);
    }

    decimal StringToDecimal(string str)
    {
        return str == "" ? -1 : Convert.ToDecimal(str);
    }

    int StringToInt(string str)
    {
        return str == "" ? -1 : Convert.ToInt32(str);
    }

    string DateTimeToString(DateTime dt)
    {
        return dt.Year == 9999 ? "" : dt.ToString("yyyy-MM-dd");
    }

    string DecimalToString(Decimal de)
    {
        return de == -1 ? "" : de.ToString();
    }

    string IntToString(int data)
    {
        return data == -1 ? "" : data.ToString();
    }

    protected string getDepartmentName(string id)
    {
        return Department.GetDepartment(id).FullName;
    }
    protected void WorkHight6_TextChanged(object sender, EventArgs e)
    {

    }
    protected void ddlClass_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindddlDriver();
    }
    protected void UnitList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindddlDriver();
    }
}
